﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Security;
using System.Web.Security;
using System.Windows.Forms;
namespace Web_cuiki
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        private DataTable table;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Membership.GetUser() == null)
            {
                this.Response.Redirect("Login.aspx");
            }
            if (!IsPostBack)
            {
                if (Session["dsChiTiet"] == null)
                {
                    NhaXuatBanDataContext db = new NhaXuatBanDataContext();
                    //List<CHI_TIET_HOA_DON> dsChiTiet = new List<CHI_TIET_HOA_DON>();
                    //List<ChiTietDonDatHangDTO> dsChiTiet = new List<ChiTietDonDatHangDTO>();
                    //CHI_TIET_HOA_DON ct1 = new CHI_TIET_HOA_DON();
                    //ct1.GiaLucMua = 12000;
                    //ct1.MaSach = 3;
                    //ct1.SoLuong = 2;
                    //var query = from sp in db.SAN_PHAMs
                    //            where sp.MaSanPham == 3
                    //            select sp;
                    //ct1.SAN_PHAM = query.FirstOrDefault();
                    //CHI_TIET_HOA_DON ct2 = new CHI_TIET_HOA_DON();
                    //ct2.GiaLucMua = 12000;
                    //ct2.MaSach = 3;
                    //ct2.SoLuong = 3;
                    //ct2.SAN_PHAM = query.FirstOrDefault();

                    //dsChiTiet.Add(ct1);
                    //dsChiTiet.Add(ct2);

                    //Session["dsChiTiet"] = dsChiTiet;
                   
                }
                
                this.tbNgay.Text = DateTime.Now.Date.ToShortDateString();
                this.BindingData();
            }

        }


        private bool loadThongTinVanChuyen()
        {
            bool rs = true;
            try
            {
                //MessageBox.Show("1", "YourBoxTitleHere", MessageBoxButtons.OK, MessageBoxIcon.Warning);
               // Response.Write("<script>alert('Hello')</script>");
                object rsTinh = WSProxy.CallWebService("http://nhomvc06.somee.com/Service1.asmx", "Service1", "DanhSachCacTinhHoTro", new object[] { });
               
                string str = WSRequest.SerializeAnObject(rsTinh);
               
                str = WSRequest.EditToBasicFormat(str);
               
                List<string> dsTinh = new List<string>();
                
                WSRequest.XMLToObject<List<string>>(ref dsTinh, str);
                for (int i = 0; i < dsTinh.Count; i++)
                {
                    ddlTinhThanh.Items.Add(dsTinh[i]);
                }
                
                object rsThung = WSProxy.CallWebService("http://nhomvc06.somee.com/Service1.asmx", "Service1", "DanhSachCacLoaiThung", new object[] { });
                str = WSRequest.SerializeAnObject(rsThung);

                str = WSRequest.EditToBasicFormat(str);
                //tbGiaVanChuyen.Text = str;
                List<string> dsThung = new List<string>();
                WSRequest.XMLToObject<List<string>>(ref dsThung, str);
                for (int i = 0; i < dsThung.Count; i++)
                {
                    ddlLoaiThung.Items.Add(dsThung[i]);
                }

                object rsLoaiVanChuyen = WSProxy.CallWebService("http://nhomvc06.somee.com/Service1.asmx", "Service1", "DanhSachCacLoaiVanChuyen", new object[] { });
                str = WSRequest.SerializeAnObject(rsLoaiVanChuyen);
                str = WSRequest.EditToBasicFormat(str);
                List<string> dsLoaiVC = new List<string>();
                WSRequest.XMLToObject<List<string>>(ref dsLoaiVC, str);
                for (int i = 0; i < dsLoaiVC.Count; i++)
                {
                    ddlLoaiVanChuyen.Items.Add(dsLoaiVC[i]);
                }
            }
            catch (Exception ex)
            {
                rs = false;
               // tbTongTien.Text = ex.Message;
               // System.Windows.Forms.MessageBox.Show(ex.Message);
                //MessageBox.Show(ex.Message, "YourBoxTitleHere", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return rs;
        }

        private string TinhPhiVanChuyen()
        {
            string rs = null;
            double gia = -1;
            if (ddlLoaiThung.SelectedIndex <= 0)
                return "Vui lòng chọn loại thùng";
            if (ddlLoaiVanChuyen.SelectedIndex <= 0)
                return "Vui lòng chọn loại vận chuyển";
            if (ddlTinhThanh.SelectedIndex <= 0)
                return "Vui lòng chọn tỉnh thành cần chuyển đến";
            string noiDen = ddlTinhThanh.SelectedItem.Text.Trim();
            //string id = (string)WSProxy.CallWebService("http://nhomvc06.somee.com/Service1.asmx", "Service1", "WSLogin", new object[] { "thaihuytan", "thaihuytan" });
            string strThamSo = ddlLoaiVanChuyen.SelectedIndex.ToString()+"_" + ddlLoaiThung.SelectedIndex.ToString() + "_1";
            gia = (double)WSProxy.CallWebService("http://nhomvc06.somee.com/Service1.asmx", "Service1", "ShippingPrice", new object[] { "Thành Phố", noiDen, strThamSo });
            if (gia > 0)
                rs = gia.ToString();
            else
                rs = "Vui lòng chọn nhà vận chuyển khác";

            return rs;
        }

        private string TinhPhiVanChuyen14()
        {
            string rs = null;
            float gia = -1;
           
            if (ddlTinhThanh.SelectedIndex <= 0)
                return "Vui lòng chọn tỉnh thành cần chuyển đến";
            string noiDen = ddlTinhThanh.SelectedItem.Text.Trim();


            gia = (float)WSProxy.CallWebService("http://vanchuyen14.somee.com/Service1.asmx", "Service1", "PhiVanChuyen", new object[] { "TP Hồ Chí Minh", noiDen });
            if (gia >= 0)
                rs = gia.ToString();
            else
                rs = "Vui lòng chọn nhà vận chuyển khác";

            return rs;
        }

        private bool loadThongTinVanChuyen14()
        {
              bool rs = true;
              try
              {
                  //object rsTinh = WSProxy.CallWebService("http://nhomvc06.somee.com/Service1.asmx", "Service1", "DanhSachCacTinhHoTro", new object[] { });
                  object rsTinh = WSProxy.CallWebService("http://vanchuyen14.somee.com/Service1.asmx", "Service1", "LayDanhSachTruSo", new object[] { });
                  string str = WSRequest.SerializeAnObject(rsTinh);
                  str = WSRequest.EditToBasicFormat(str);
                  List<string> dsTinh = new List<string>();
                  WSRequest.XMLToObject<List<string>>(ref dsTinh, str);
                  for (int i = 0; i < dsTinh.Count; i++)
                  {
                      ddlTinhThanh.Items.Add(dsTinh[i]);
                  }

                  
              }
              catch (Exception ex)
              {
                  rs = false;
              }
              return rs;
        }

        private List<ChiTietDonDatHangDTO> stringToListChiTiet(string str)
        {
            List<ChiTietDonDatHangDTO> rs = new List<ChiTietDonDatHangDTO>();
            str = WSRequest.EditToBasicFormat(str);
            WSRequest.XMLToObject<List<ChiTietDonDatHangDTO>>(ref rs, str);
            return rs;
        }

        private void BindingData()
        {

            table = new DataTable();
            table.Columns.Add("STT");
            table.Columns.Add("Mã sách");
            //table.Columns.Add("Tên sách");
            table.Columns.Add("Giá bán");
            table.Columns.Add("Số lượng");
            table.Columns[0].AutoIncrement = true;
            table.Columns[0].AutoIncrementSeed = 1;
            table.Columns[0].ReadOnly = true;
            table.Columns[1].DataType = System.Type.GetType("System.Int32");
            table.Columns[2].DataType = System.Type.GetType("System.Double");
            table.Columns[3].DataType = System.Type.GetType("System.Int32");

            string strds = (string)Session["dsChiTiet"];
            List<ChiTietDonDatHangDTO> dsChiTiet = stringToListChiTiet(strds);
            if (dsChiTiet != null)
            {
                for (int i = 0; i < dsChiTiet.Count; i++)
                {
                    DataRow row = table.NewRow();

                    row["Mã sách"] = dsChiTiet[i].MaTaiLieu;
                   // row["Tên sách"] = dsChiTiet[i].SAN_PHAM.TenSanPham;
                    row["Giá bán"] = dsChiTiet[i].DonGia;
                    row["Số lượng"] = dsChiTiet[i].SoLuong;
                    table.Rows.Add(row);
                }


            }
            GridView1.DataSource = table;
            GridView1.DataBind();


        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;

            BindingData();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            BindingData();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

        }


        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int seletedIndex = e.RowIndex;
            if (Session["dsChiTiet"] != null)
            {

                string strds = (string)Session["dsChiTiet"];
                List<ChiTietDonDatHangDTO> dsChiTiet = stringToListChiTiet(strds);
                if (dsChiTiet != null && dsChiTiet.Count > 0 && seletedIndex < dsChiTiet.Count && seletedIndex >= 0)
                {
                    dsChiTiet.RemoveAt(seletedIndex);
                    string str = WSRequest.ObjectToXML(dsChiTiet.ToArray<ChiTietDonDatHangDTO>());
                    Session["dsChiTiet"] = str;
                }
            }
            BindingData();
        }
     

        private string datLenh()
        {
            string rs = null;
            try
            {
                if (ddlLoaiThung.SelectedIndex <= 0)
                    return rs;
                if (ddlLoaiVanChuyen.SelectedIndex <= 0)
                    return rs;
                if (ddlTinhThanh.SelectedIndex <= 0)
                    return rs;
                string noiDen = ddlTinhThanh.SelectedItem.Text.Trim();
                
                string strThamSo = ddlLoaiVanChuyen.SelectedIndex.ToString() + "_" + ddlLoaiThung.SelectedIndex.ToString() + "_1";
                string id = (string)WSProxy.CallWebService("http://nhomvc06.somee.com/Service1.asmx", "Service1", "WSLogin", new object[] { "thaihuytan", "thaihuytan" });
                DateTime ngayNhan = DateTime.Parse(tbNgay.Text.Trim());

                rs = (string)WSProxy.CallWebService("http://nhomvc06.somee.com/Service1.asmx", "Service1", "PlaceTransportCommand", new object[] { id, "Thành Phố", noiDen, strThamSo,DateTime.Now, ngayNhan });
            }
            catch (Exception ex)
            {
                rs = null;
            }
            return rs;
        }


        private string datLenh14()
        {
            string rs = null;
            try
            {
                
                if (ddlTinhThanh.SelectedIndex <= 0)
                    return rs;
                string noiDen = ddlTinhThanh.SelectedItem.Text.Trim();
                
                string strThamSo = tbTenNguoiNhan.Text.Trim();
                string id = (string)WSProxy.CallWebService("http://vanchuyen14.somee.com/Service1.asmx", "Service1", "DangNhap", new object[] { "bloomsbury", "tmdt" });
                DateTime ngayNhan = DateTime.Parse(tbNgay.Text.Trim());

                rs = (string)WSProxy.CallWebService("http://vanchuyen14.somee.com/Service1.asmx", "Service1", "DatLenhVanChuyen", new object[] { id, "TP Hồ Chí Minh", noiDen, strThamSo, ngayNhan });
            }
            catch (Exception ex)
            {
                rs = null;
            }
            return rs;
        }

        private string createContentMail(string link)
        {
            string rs = "";
            string strds = (string)Session["dsChiTiet"];
            List<ChiTietDonDatHangDTO> dsChiTiet = stringToListChiTiet(strds);
            if (dsChiTiet != null && dsChiTiet.Count > 0)
            {
                rs += "<p>Link để theo dõi hàng được vận chuyên :<a href='"+link+"'>"+link+"</a></p>";
                rs += "<table>";
                rs += "<tr>" +
                    "<td>STT</td>" +
                    "<td>Mã sách</td>" +
                    "<td>Tên sách</td>" +
                    "<td>Giá bán</td>" +
                    "<td>Số lượng</td>" +
                    "</tr>";
                for (int i = 0; i < dsChiTiet.Count; i++)
                {
                    rs += "<tr>";
                    rs += "<tr>" +
                   "<td>" + (i + 1) + "</td>" +
                   "<td>" + (dsChiTiet[i].MaTaiLieu) + "</td>" +
                   
                   "<td>" + dsChiTiet[i].DonGia + "</td>" +
                   "<td>" + dsChiTiet[i].SoLuong + "</td>" +
                   "</tr>";
                    rs += "</tr>";
                }
            }


            return rs + "</table>";
        }
        public string Send_Email(string SendFrom, string SendTo, string Subject, string Body)
        {
            try
            {

                System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage(SendFrom, SendTo,
                Subject, Body);

                MyMailMessage.IsBodyHtml = true;


                System.Net.NetworkCredential mailAuthentication = new
                System.Net.NetworkCredential("gaoxteen@gmail.com", "vanhien179");

                System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);

                //Enable SSL
                mailClient.EnableSsl = true;

                mailClient.UseDefaultCredentials = false;

                mailClient.Credentials = mailAuthentication;

                mailClient.Send(MyMailMessage);
                return "thanhcong";
            }
            catch
            {
                return "thatbai";
            }
        }


        protected void btTinhPhi_Click(object sender, EventArgs e)
        {
            this.tbTongTien.Text = "";
            this.tbGiaVanChuyen.Text = "";
            if(DropDownList1.SelectedIndex == 1)
                this.tbGiaVanChuyen.Text = this.TinhPhiVanChuyen();
            if(DropDownList1.SelectedIndex == 2)
                this.tbGiaVanChuyen.Text = this.TinhPhiVanChuyen14();
            try
            {
                float phiVanChuyen = float.Parse(tbGiaVanChuyen.Text.Trim());
                if (Session["dsChiTiet"] != null)
                {
                    string strds = (string)Session["dsChiTiet"];
                    List<ChiTietDonDatHangDTO> dsChiTiet = stringToListChiTiet(strds);
                    {
                        double tongTien = phiVanChuyen;
                        for (int i = 0; i < dsChiTiet.Count; i++)
                        {
                            tongTien += dsChiTiet[i].DonGia * dsChiTiet[i].SoLuong;
                        }
                        this.tbTongTien.Text = tongTien.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                this.tbTongTien.Text = "Tính tiền lỗi, vui lòng thử lại sau ^..^";
            }

        }

        protected void btXacNhan_Click(object sender, EventArgs e)
        {

            //List<CHI_TIET_HOA_DON> dsChiTiet = (List<CHI_TIET_HOA_DON>)Session["dsChiTiet"];
            string strds = (string)Session["dsChiTiet"];
            List<ChiTietDonDatHangDTO> dsChiTiet = stringToListChiTiet(strds);
            if (dsChiTiet != null && dsChiTiet.Count > 0)
            {
                NhaXuatBanDataContext db = new NhaXuatBanDataContext();
                db.DeferredLoadingEnabled = false;
                //CHI_TIET_HOA_DON ct1 = new CHI_TIET_HOA_DON();
                //ct1.GiaLucMua = 12000;
                //ct1.MaSach = 3;
                //ct1.SoLuong = 2;
                //var query = from sp in db.SAN_PHAMs
                //            where sp.MaSanPham == 3
                //            select sp;
                //ct1.SAN_PHAM = query.FirstOrDefault();
                //dsChiTiet.Add(ct1);
                System.Data.Linq.Table<HOA_DON> table = db.GetTable<HOA_DON>();
                string rs = null;
                if (DropDownList1.SelectedIndex == 1)
                    rs = this.datLenh();
                if (DropDownList1.SelectedIndex == 2)
                    rs = this.datLenh14();
                if (rs != null)
                {
                    string contentmail = this.createContentMail(rs);
                    string email=Membership.GetUser().Email;
                    string rsMail = this.Send_Email("gaoxteen@gmail.com",email, "NXB16 - Thông tin hóa đơn", contentmail);
                    if (rsMail.Equals("thanhcong"))
                    {
                        HOA_DON hd = new HOA_DON();
                        string username = Membership.GetUser().UserName;
                        hd.TenDangNhap = username;
                        hd.TinhTrang = false;
                        hd.NgayGiaoHang = DateTime.Parse(tbNgay.Text);
                        hd.NgayDatHang = DateTime.Now;
                        hd.MaNhaVanChuyen = DropDownList1.SelectedIndex;
                        hd.TongTien = float.Parse(tbTongTien.Text.Trim());

                        //db.HOA_DONs.Attach(hd);
                        table.InsertOnSubmit(hd);
                        db.SubmitChanges();
                        System.Data.Linq.Table<CHI_TIET_HOA_DON> tableChiTiet = db.GetTable<CHI_TIET_HOA_DON>();
                        for (int i = 0; i < dsChiTiet.Count; i++)
                        {
                            CHI_TIET_HOA_DON ct = new CHI_TIET_HOA_DON();
                            ct.GiaLucMua = dsChiTiet[i].DonGia;
                            ct.MaSach = dsChiTiet[i].MaTaiLieu;
                            ct.SoLuong = dsChiTiet[i].SoLuong;
                            ct.MaHoaDon = HoaDonDAO.laydsHoaDonTheoTenKhachHang(username).Last().MaHoaDon;
                            tableChiTiet.InsertOnSubmit(ct);
                        }
                        //db.SubmitChanges();

                        Session.Remove("dsChiTiet");
                        db.SubmitChanges();
                        Response.Redirect("XacNhanThanhCong.aspx");
                    }
                    else
                        Response.Redirect("ErrorTransport.aspx");
                }
            }
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.DropDownList1.SelectedIndex == 1)
            {
                if (!this.loadThongTinVanChuyen())
                {
                    Response.Redirect("ErrorTransport.aspx");
                    this.ddlLoaiThung.Items.Clear();
                    this.ddlLoaiVanChuyen.Items.Clear();
                    this.ddlTinhThanh.Items.Clear();
                }
            }
            if (this.DropDownList1.SelectedIndex == 2)
            {
                if (!this.loadThongTinVanChuyen14())
                {
                    Response.Redirect("ErrorTransport.aspx");
                    this.ddlLoaiThung.Items.Clear();
                    this.ddlLoaiVanChuyen.Items.Clear();
                    this.ddlTinhThanh.Items.Clear();
                }
            }
        }

    }
}
